package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

func (user *User) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("CreateTime", time.Now().Unix())
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

//修改时自动执行
func (user *User) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

func AddUser(username string, password string) bool {
	db.Create(&User{
		Username: username,
		Password: password,
	})
	return true
}

func EditUser(id int, data map[string]interface{}) bool {
	db.Model(&User{}).Where("id=?", id).
		Update(&User{
			Username: data["username"].(string),
			Password: data["password"].(string),
			Status:   data["status"].(int),
		})

	return true
}

func DeleteUser(id int) bool {
	db.Where("id=?", id).Delete(&User{})
	return true
}

func ExistUserById(id int) bool {
	user := User{}
	db.Where("id=?", id).Find(&user)
	if user.ID > 0 {
		return true
	}
	return false
}

func ExistUserByName(userName string) bool {
	user := User{}
	db.Where("username=?", userName).Find(&user)
	if user.ID > 0 {
		return true
	}
	return false
}

func GetUserList(pagenum int, pagesize int, maps interface{}) (user []User) {
	db.Where(maps).Offset(pagenum).Limit(pagesize).Find(&user)
	return
}

func GetUser(id int) (*User, error) {
	var user User
	err := db.Model(&User{}).Where("id=?", id).Find(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func GetUserTotal(maps interface{}) (count int) {
	db.Model(&User{}).Where(maps).Count(&count)
	return
}
